<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleFormEdit({})" v-auth="'btn:add:guabiao'">
          <Icon icon="fluent:add-12-filled" /> {{ t('发起挂表申请') }}
        </a-button>
        <a-button type="primary" @click="handleFormLog({})" v-auth="'btn:query:biaowurizhi'">
          <Icon icon="fluent:search-12-filled" /> {{ t('表务日志查询') }}
        </a-button>

         <a-popconfirm
          title="是否确认刷新表务日志？"
          ok-text="是"
          cancel-text="否"
          @confirm="handleFormRefresh()"
        >
          <a-button type="primary" v-auth="'btn:refresh:biaowurizhi'">
            <Icon icon="fluent:content-view-20-filled" /> {{ t('刷新表务日志') }}
          </a-button>
        </a-popconfirm>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ id: record.id })">
          {{ record.name }}
        </a>
      </template>

      <template #projectno="{ record }">
        <!-- <a @click="handleDetailsForm(record)">
          <span style="text-decoration: underline; margin-right: 5px">查看</span>
        </a>
        {{ record.projectno }} -->
        <a @click="handleDetailsForm(record)">
          {{ record.projectno }}
        </a>
      </template>
      <template #uploadFile1="{ record }">
        <BasicUpload
          v-model:value="record.dataMap"
          disabled
          :bizKey="record.id"
          :bizType="'PmWaterMeter_image'"
          :uploadType="'image'"
          :loadTime="record.__t"
          :showPreview="true"
          :isPreview="false"
          :emptyHidePreview="true"
        />
      </template>
      <!--  parseTime('{y}-{m}-{d} {h}:{i}:{s}') -->
      <template #installtime="{ record }">
        {{ formatDate(record.installtime) }}
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <InputFormEdit @register="registerDrawerEdit" @success="handleSuccessEdit" />
    <BpmRuntimeTrace @register="registerTraceModal" />
    <LogList @register="registerDrawerLog" @success="handleSuccessLog" />

    <component
      :is="inputFormComponent"
      v-model:visible="inputFormVisible"
      @register="registerDrawerBpmMyTask"
      @success="handleSuccess"
    />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsProcessMeterPmWatermeterList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, ComponentOptions, shallowRef, onMounted, watch } from 'vue';
  import { bpmTaskDefForm } from '/@/api/bpm/myTask';
  import { dynamicImport } from '/@/router/helper/routeHelper';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import qs from 'qs';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    pmWatermeterDelete,
    pmWatermeterListData,
    pmWatermeterRefreshLog,
  } from '/@/api/process/meter/pmWatermeter';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { BpmRuntimeTrace } from '/@/components/Bpm';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import InputFormEdit from './createForm.vue';
  import LogList from './listLog.vue';
  import { BasicUpload } from '/@/components/Upload';
  import { useUserStore } from '/@/store/modules/user';
  const userStore = useUserStore();

  const { t } = useI18n('process.meter.pmWatermeter');
  const { showMessage } = useMessage();
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    // value: router.currentRoute.value.meta.title || t('挂表管理'),
    value: t('挂表管理'),
  };
  const props = defineProps({
    projectno: { type: String, default: '' },
  });

  // 时间格式化日期，只保留年月日
  const formatDate = (date: string) => {
    if (!date) return '';
    const dateObj = new Date(date);
    const year = dateObj.getFullYear();
    const month = dateObj.getMonth() + 1;
    const day = dateObj.getDate();
    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('工程编号'),
        field: 'projectno',
        component: 'Input',
      },
      {
        label: t('项目名称'),
        field: 'name',
        component: 'Input',
      },
      {
        label: t('状态'),
        field: 'status',
        component: 'Select',
        componentProps: {
          dictType: 'bpm_biz_status',
          allowClear: true,
          onChange: handleSuccess,
        },
      },
      {
        label: t('安装人'),
        field: 'pername',
        component: 'Input',
        show: false,
      },
      {
        label: t('创建时间'),
        field: 'createDate',
        component: 'DatePicker',
        componentProps: {
          format: 'YYYY-MM-DD HH:mm',
          // showTime: { format: 'HH:mm' },
        },
        ifShow: false,
      },
      {
        label: t('申请备注'),
        field: 'remarks',
        component: 'Input',
        ifShow: false,
      },
      {
        label: t('picno'),
        field: 'picno',
        component: 'Input',
        ifShow: false,
      },
      {
        label: t('申请结果'),
        field: 'checkresult',
        component: 'Input',
        ifShow: false,
      },
      {
        label: t('安装人编号'),
        field: 'perno',
        component: 'Input',
        ifShow: false,
      },
      {
        label: t('安装人名称'),
        field: 'pername',
        component: 'Input',
        ifShow: false,
      },
      {
        label: t('申请挂表时间'),
        field: 'installtime',
        component: 'DatePicker',
        componentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
        ifShow: false,
      },
      {
        label: t('验收结果'),
        field: 'gbresult',
        component: 'Input',
        ifShow: false,
      },
      {
        label: t('picno2'),
        field: 'picno2',
        component: 'Input',
        ifShow: false,
      },
      {
        label: t('picno3'),
        field: 'picno3',
        component: 'Input',
        ifShow: false,
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('状态'),
      dataIndex: 'status',
      key: 'a.status',
      sorter: true,
      width: 80,
      align: 'center',
      dictType: 'bpm_biz_status',
    },

    {
      title: t('工程编号'),
      dataIndex: 'projectno',
      key: 'a.projectno',
      sorter: true,
      width: 130,
      align: 'left',
      slot: 'projectno',
    },
    {
      title: t('项目名称'),
      dataIndex: 'name',
      key: 'a.name',
      sorter: true,
      width: 260,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('创建时间'),
      dataIndex: 'createDate',
      key: 'a.createtime',
      sorter: true,
      width: 140,
      align: 'left',
    },

    {
      title: t('安装人编号'),
      dataIndex: 'perno',
      key: 'a.perno',
      sorter: true,
      width: 100,
      align: 'left',
      ifShow: false,
    },
    {
      title: t('安装人'),
      dataIndex: 'pername',
      key: 'a.pername',
      sorter: true,
      width: 60,
      align: 'left',
    },
    {
      title: t('申请挂表时间'),
      dataIndex: 'installtime',
      key: 'a.installtime',
      sorter: true,
      width: 80,
      align: 'center',
      slot: 'installtime',
    },
    {
      title: t('申请说明'),
      dataIndex: 'remarks',
      key: 'a.remarks',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('申请结果'),
      dataIndex: 'checkresult',
      key: 'a.checkresult',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('验收结果'),
      dataIndex: 'gbresult',
      key: 'a.gbresult',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('申请附件'),
      dataIndex: 'assayupdate',
      key: 'a.assayupdate',
      sorter: true,
      width: 100,
      align: 'center',
      fixed: 'right',
      slot: 'uploadFile1',
    },
    {
      title: t('状态'),
      dataIndex: 'status',
      key: 'a.status',
      sorter: true,
      width: 60,
      align: 'center',
      dictType: 'bpm_biz_status',
      fixed: 'right',
    },
    {
      title: t('picno'),
      dataIndex: 'picno',
      key: 'a.picno',
      sorter: true,
      width: 130,
      align: 'left',
      ifShow: false,
    },
    {
      title: t('picno2'),
      dataIndex: 'picno2',
      key: 'a.picno2',
      sorter: true,
      width: 130,
      align: 'left',
      ifShow: false,
    },
    {
      title: t('picno3'),
      dataIndex: 'picno3',
      key: 'a.picno3',
      sorter: true,
      width: 130,
      align: 'left',
      ifShow: false,
    },
    {
      title: t('创建时间'),
      dataIndex: 'createDate',
      key: 'a.createDate',
      sorter: true,
      width: 130,
      align: 'left',
      ifShow: false,
    },
  ];

  const actionColumn: BasicColumn = {
    width: 100,
    align: 'left',
    actions: (record: Recordable) => [
      {
        icon: 'fluent:flowchart-20-regular',
        title: t('流程追踪'),
        onClick: handleTrace.bind(this, record),
        ifShow: () => record.status != '9',
      },
      {
        icon: 'mdi:checkbox-marked-outline',
        title: t('任务办理'),
        onClick: handleBpmMyTask.bind(this, { id: record.id }),
        ifShow: () => record.status == '4' || record.status == '5' || record.status == '6',
      },
      {
        icon: 'clarity:note-edit-line',
        title: t('编辑挂表'),
        onClick: handleFormEdit.bind(this, { id: record.id }),
        auth: 'btn:edit:guabiao',
        ifShow: () => record.status == '9',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除挂表'),
        popConfirm: {
          title: t('是否确认删除挂表'),
          confirm: handleDelete.bind(this, { id: record.id }),
        },
        auth: 'btn:delete:guabiao',
        ifShow: () => record.status == '9',
      },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerDrawerEdit, { openDrawer: openDrawerEdit }] = useDrawer();
  const [registerDrawerLog, { openDrawer: openDrawerLog }] = useDrawer();

  const [registerTable, { reload, getForm, getSelectRows }] = useTable({
    api: pmWatermeterListData,
    beforeFetch: (params) => {
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    rowSelection: { type: 'radio' },
    immediate: false,
  });

  const [registerDrawerBpmMyTask, { setDrawerData }] = useDrawer();
  const inputFormComponent = shallowRef<Nullable<any>>(null);
  const inputFormVisible = ref<Boolean>(false);

  async function handleBpmMyTask(record: Recordable) {
    const data = await bpmTaskDefForm({ formKey: 'Flow_PmWaterMeter', bizKey: record.id });
    if (data.result == 'true') {
      const url = data.pcUrl;
      const idx = url.indexOf('?');
      // component
      let component: ReturnType<typeof defineComponent>;
      const compStr = idx == -1 ? url : url.substring(0, idx);
      if (compStr && compStr != '') {
        const imp = dynamicImport(compStr);
        if (imp) component = createAsyncComponent(imp);
      }
      // params
      let params = {};
      const paramStr = idx == -1 ? '' : url.substring(idx + 1);
      if (paramStr && paramStr != '') {
        params = qs.parse(paramStr);
      }
      // open
      if (component) {
        inputFormComponent.value = component;
        inputFormVisible.value = true;
        setDrawerData(params);
      }
    } else {
      showMessage(data.message);
    }
  }

  function handleDetailsForm(record: Recordable) {
    router.push({
      path: '/proj/info/pmProjectinformation/detailsForm',
      query: {
        id: record.projInfo.id,
        code: record.projectno,
        tabTitle: `项目详情(${record.projectno})`,
      },
    });
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  function handleFormEdit(record: Recordable) {
    openDrawerEdit(true, record);
  }

  function handleFormLog(record: Recordable) {
    if (getSelectRows().length == 1) {
      var selIds = ref('');
      selIds.value = getSelectRows()[0].projectno;
      console.log(selIds.value, 'selIds.value');
      openDrawerLog(true, { projectno: selIds.value });
      handleSuccess();
    } else {
      showMessage('请选择一行数据！！');
    }
  }

  function handleSuccessEdit() {
    openDrawerEdit(true, {});
    handleSuccess();
  }

  async function handleDelete(record: Recordable) {
    const res = await pmWatermeterDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  function handleSuccess() {
    reload();
  }

  const [registerTraceModal, { openModal: traceModel }] = useModal();

  function handleTrace(record: Recordable) {
    traceModel(true, { formKey: 'Flow_PmWaterMeter', bizKey: record.id });
  }

  async function handleFormRefresh() {
    if (getSelectRows().length) {
      var selIds = ref('');
      getSelectRows().forEach((item) => {
        selIds.value += item.projectno;
      });
      const res = await pmWatermeterRefreshLog({ selIds: selIds.value });
      showMessage('刷新日志成功');
      handleSuccess();
    } else {
      showMessage('请选择一行数据！！');
    }
  }
  watch(
    () => props.projectno,
    () => {
      handleProjecte();
    },
  );

  onMounted(async () => {
    handleProjecte();
  });

  async function handleProjecte() {
    await getForm().setFieldsValue({
      projectno: props.projectno ? props.projectno : userStore.getProjecte.code,
      status: '',
    });
    reload();
    await getForm().setFieldsValue({
      projectno: props.projectno ? props.projectno : userStore.getProjecte.code,
      status: '',
    });
  }
</script>
